/**
 * 
 */
package it.battlehorse.scripting.view;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.TimeUnit;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.ui.PlatformUI;

import static it.battlehorse.scripting.ScriptingActivator.*;

/**
 * Provides automatic script refresh functionality for scripted views. 
 * <br />
 * <b>Note:</b> the button is disabled for internal scripts
 * 
 * @author battlehorse
 *
 */
public class AutoRefreshAction extends Action {
	
	private IAction action;
	private ScriptProxyView view;
	
	private long lastModified;
	 
	public AutoRefreshAction(ScriptProxyView view, IAction action){
		super("Auto refresh",AS_CHECK_BOX);
		this.setToolTipText("Auto Refresh script");
		this.action = action;
		this.view = view;
		this.setImageDescriptor(imageDescriptorFromPlugin(PLUGIN_ID, "icons/autorefresh.png"));
		
		try {
			URI uri = new URI(view.getScript().getURI());
			if (!uri.isAbsolute() || "file".equals(uri.getScheme())) {
				this.setToolTipText("Auto refresh is disabled for internal scripts");
				this.setEnabled(false);
			}
			else {
				File f =new File(uri);	
				lastModified = f.exists() ? f.lastModified() : -1;
			}
		}
		catch(URISyntaxException e) {} 
		
	}
			
	@Override
	public void run() {
		action.setEnabled(!this.isChecked());
		
		if (this.isChecked()) {
			// toggle down
			view.getScheduledService().scheduleWithFixedDelay(new Runnable() {
				public void run() {
					try {
						File f =new File(new URI(view.getScript().getURI()));	// we are sure that URI is an absolute file:// , otherwise the action will be disabled
						if (f.exists() && f.lastModified() > lastModified ) {
							lastModified = f.lastModified();
							PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
								public void run() { view.refresh(); }
							});							
						}
					}
					catch(URISyntaxException e) {} 
				}
			}, 200, 200, TimeUnit.MILLISECONDS);
		}
		else {		
			// toggle up
			view.cycleScheduledService();
		}
	}

}
